package com.isoft.dao;
import com.isoft.pojo.Goods;
import lombok.Data;

import java.io.*;
import java.util.ArrayList;

@Data
//使用 ObjectOutputStream 写文件 FileOutputStream
public class GoodsDAO {
    String fileName = "d:/goodsInfo1.txt";
    File file;

    public GoodsDAO() {
// InputStream stream =
        Class.class.getResourceAsStream(fileName);
        file = new File(fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
                System.out.println("文件初始化成功！");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public void addGoods(Goods goods) {
        System.out.println(goods);
        try {//Bug 需要修改完善
            FileOutputStream fileOutputStream = new
                    FileOutputStream(file);
            ObjectOutputStream outputStream = new
                    ObjectOutputStream(fileOutputStream);
            ArrayList<Goods> list1=new ArrayList<>();
            list1.add(goods);
            outputStream.writeObject(list1);
            outputStream.flush();
            outputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("商品入库成功！");
    }

    public void updateGoods(Goods goods) {

    }

    public void deleteGoods(String goodsID) {

    }

    public void findGoodsByID(String goodsID) {
        try {
            int flag=0;
            FileInputStream fileIutputStream = new
                    FileInputStream(file);
            ObjectInputStream inputStream = new
                    ObjectInputStream(fileIutputStream);
            ArrayList<Goods> list = (ArrayList<Goods>)
                    inputStream.readObject();
            if (list != null) {
                for (int i=0;i<list.size();i++){
                    Goods goods = list.get(i);
                    if (goodsID.equals(goods.getGoodsId())){//
                        System.out.println("你要查询的商品信息为： ");
                        System.out.println(goods);
                        flag=1;
                        break;
                    }
                }
                if (flag==0){
                    System.out.println("您输入的商品 ID 有误，请重 试！");
                }
            }
            inputStream.close();
            fileIutputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void findAllGoods() {

    }
}